﻿@{
    Layout = "_Layout";
    ViewData["Title"] = "笔记软件";
}
@section Styles
{
    <link href="~/css/index.css" rel="stylesheet" />
}
<div class="content-area">
    <div class="notes-list">
        <div class="list-header">
            <p>{{i18n.t('共')}} {{ filteredNotes.length }} {{i18n.t('条笔记')}}</p>
            <div>
                <el-button size="mini" type="primary" v-on:click="createNewNote" icon="el-icon-plus"> {{i18n.t('新建笔记')}}</el-button>
            </div>
        </div>

        <div class="notes-container">
            <transition-group name="slide-fade" tag="div">
                <div v-for="note in filteredNotes" v-bind:key="note.id" class="note-item" v-bind:class="{ active: activeNoteId === note.id, 'new-note': note.new }"
                     v-on:click="selectNote(note)">
                    <div class="note-title">
                        <span>{{ note.title }}</span>
                        <span class="note-date">{{ formatDate(note.createTime) }}</span>
                        <el-dropdown size="mini" v-on:command ="handleCommand">
                            <span class="el-dropdown-link">
                                {{i18n.t('操作')}}<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item :command="'edit_' + note.id" icon="el-icon-edit" :size="size">{{i18n.t('编辑')}}</el-dropdown-item>
                                <el-dropdown-item :command="'del_' + note.id" icon="el-icon-delete" :size="size">{{i18n.t('删除')}}</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>

                        @* <el-button-group>
                            <el-button type="primary" icon="el-icon-edit" :size="size" v-on:click="editNote(note)"></el-button>
                            <el-button type="danger" icon="el-icon-delete" :size="size"></el-button>
                        </el-button-group> *@
                    </div>
                    <div class="note-tags">
                        <el-tag v-for="(tag, index) in note.tags" :key="index" :type="getTagType(tag,index)" size="small"> {{ tag.tagName }} </el-tag>
                    </div>
                </div>
            </transition-group>
        </div>
    </div>

    <div class="note-editor" v-if="activeNote">
        <div class="editor-header">
            <div class="editor-header-content">
                <div v-text="activeNote.title" style="white-space: pre-wrap;"></div>
            </div>
        </div>
        <div class="editor-content">
            <div class="pre" v-text="activeNote.content" style="white-space: pre-wrap;"></div>
        </div>
    </div>
</div>


@section Scripts {
    <script>

        new Vue({
            el: '#app',
            data: {
                size:'mini',
                activeMenu: 0,
                activeNoteId: null,
                searchQuery: '',
                unreadNotifications: 3,
                newTag: '',
                wordCount: 0,
                availableTags: [],
                notes: [],
                noteData:{ },
                noteDataOption:{
                     span:24,
                     labelWidth:'110',
                     column: [
                        { prop: "id", search: false, hide: true, type: "number", display: false, showColumn: false, },
                        { prop: "categoryId", value:'@ViewData["id"]', search: false, hide: true, type: "number", display: false, showColumn: false, },

                        { label: `${Vue.prototype.i18n.t('标题')}`, prop: 'title', type: 'input', span: 24, rules: [{ required: true, message:`${Vue.prototype.i18n.t('不能为空')}`, trigger: "blur" }] },
                        { label: `${Vue.prototype.i18n.t('标签')}`, prop: 'tagIds',type: 'select',multiple:true,span:24, props:{ label:'tagName',value:'id',key:"id" }, dicUrl:`/tag/list`,  },
                        { label: `${Vue.prototype.i18n.t('内容')}`, prop: 'content', type: 'textarea', span: 24, rows:10,rules: [{ required: true, message:`${Vue.prototype.i18n.t('不能为空')}`, trigger: "blur" }] },
                     ]
                },
            },
            computed: {
                activeNote() {
                        return this.notes.find(note => note.id === this.activeNoteId);
                },
                filteredNotes() {
                    let filtered = [...this.notes];

                    if (this.searchQuery) {
                        const query = this.searchQuery.toLowerCase();
                        filtered = filtered.filter(note =>
                            note.title.toLowerCase().includes(query) ||
                            note.preview.toLowerCase().includes(query) ||
                            note.content.toLowerCase().includes(query) ||
                            note.tags.some(tag => tag.toLowerCase().includes(query))
                        );
                    }

                    return filtered.sort((a, b) => b.date - a.date);
                }
            },
            created() {
                this.loadTagData();
                this.loadData();
            },
            methods: {
                loadData(){
                    this.$http.post(`/note/pages`,{ categoryId:'@ViewData["id"]',pageSize:5000,}).then((res) => {
                        var data = res.rows || [];
                         this.notes=data
                         if(data.length>0){
                             this.activeNoteId=data[0].id;
                         }
                         this.loading = false;
                     }).catch(e => {
                         console.log(e);
                     });
                },
                loadTagData(){
                    this.$http.get(`/tag/list`,{ pageSize:50 }).then((res) => {
                        var data = res || [];
                        this.availableTags=data
                        this.loading = false;
                     }).catch(e => {
                         console.log(e);
                     });
                },
                selectNote(note) {
                    if (note.new) {
                        note.new = false;
                    }
                    this.activeNoteId = note.id;
                },
                createNewNote(){
                   this.$DialogForm.show({
                        title:`${Vue.prototype.i18n.t('新增笔记')}`,
                        width: '680px',
                        fullscreen: true,
                        data: {},
                        option: this.noteDataOption,
                        callback:(res)=>{
                            this.$http.post("/note/add",res.data).then((rdata) => {
                                if(rdata){
                                    this.loadData();
                                    res.done()
                                    setTimeout(() => {
                                        this.$message.success(`${Vue.prototype.i18n.t('操作完成')}`)
                                        res.close()
                                    }, 1000)
                                }else{
                                    res.done()
                                }
                            });
                        }
                    })
                },
                editNote(d){
                   this.$DialogForm.show({
                        // dialogMenuPosition: 'right',
                        title: `${Vue.prototype.i18n.t('编辑笔记')}`,
                        width: '980px',
                        // fullscreen:true,
                        data:{id:d.id,title:d.title,tagIds:d.tagIds,content:d.content},
                        option: this.noteDataOption,
                        callback:(res)=>{
                            this.$http.post("/note/update",res.data).then((rdata) => {
                                if(rdata)
                                {
                                    this.loadData();
                                    res.done()
                                    setTimeout(() => {
                                        this.$message.success(`${Vue.prototype.i18n.t('操作完成')}`)
                                        res.close()
                                    }, 1000)
                                }else{
                                    res.done()
                                }
                            });
                        }
                    })
                },
                handleCommand(command) {
                    if (command.startsWith('edit_')) {
                      const noteId = command.split('edit_')[1];
                      this.editNote(this.getNoteById(noteId));
                    }
                    else if (command.startsWith('del_')) {
                      const noteId = command.split('del_')[1];
                      this.handleRowDel(noteId)
                    }
                },
                handleRowDel(noteId) {
                    this.$confirm(this.i18n.t('confirmdelete'), this.i18n.t('tips'), { confirmButtonText: this.i18n.t('determine'), cancelButtonText: this.i18n.t('cancel'), type: 'warning', customClass: "elmessagebox" }).then(() => {
                        let data = { id: noteId };
                        this.$http.delete("/note/delete", { data, headers: { 'Content-Type': 'application/json' } }).then((res) => {
                            if (res == true) {
                                this.$message({ message: `${this.i18n.t('submit_success')}`, center: true, type: 'success' });
                                this.loadData();
                            }
                        });
                    }).catch(_ => { loading(); console.info(_); })
                },
                getNoteById(id) {
                    const note = this.notes.find(n => `${n.id}` === `${id}`);
                    return note ? JSON.parse(JSON.stringify(note)) : null;
                },
                formatDate(date) {
                    const today = new Date();
                    const noteDate = new Date(date);
                    if (noteDate.toDateString() === today.toDateString()) {
                        return `${Vue.prototype.i18n.t('今天')}`;
                    }

                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    if (noteDate.toDateString() === yesterday.toDateString()) {
                        return `${Vue.prototype.i18n.t('昨天')}`;
                    }

                    return noteDate.toLocaleDateString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit'
                    });
                },

                formatTime(date) {
                    return new Date(date).toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                },
                getTagType(tag,index) {
                    const tagTypes = {
                        '0': 'primary',
                        '1': 'success',
                        '2': 'warning',
                        '3': 'danger',
                        '4': 'info'
                    }
                    return tagTypes[index] || '';
                }
            },
        });
    </script>
    }
